package UDP.UDP3;


import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpClientSocket {
    private DatagramSocket socket;
    private String serverIp;//服务器IP地址
    private int port;//服务器端口号
    public UdpClientSocket(String serverIp, int port) throws SocketException {
        //绑定端口号和IP地址
        this.socket = new DatagramSocket();
        this.serverIp =serverIp;
        this.port = port;
    }
    //启动客户端
    public void start() throws IOException {
        Scanner in = new Scanner(System.in);
        while(true) {
            //1.构造请求
            System.out.print("->");//模拟客户端终端
            String request = in.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(this.serverIp), this.port);
            //2.发送请求
            socket.send(requestPacket);
            //3.接收响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            //4.打印日志
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpClientSocket udpClientSocket = new UdpClientSocket("127.0.0.1", 8080);
        udpClientSocket.start();
    }

}
